package com.woyao;

import android.Manifest;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.woyao.core.model.LoginResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

/**
 * A login screen that offers login via email/password.
 */
public class PhoneLoginActivity extends AppCompatActivity  {

    String mobile = "";
    // UI references.
    private Button directBtn;
    private  TextView mobileTxt;
    private CheckBox agreeCkb;
    private Intent intent;
    ProgressDialog progressDialog;

    private static final int PERMISSION_REQUEST_PHONE = 2;
    List<String> mPermissionList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_phone);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true);
        intent  = new Intent(PhoneLoginActivity.this, MainActivity.class);

        mobileTxt = (TextView) findViewById(R.id.phone_number);
   //     populateAutoComplete();

        agreeCkb = (CheckBox) findViewById(R.id.checkBox);
        directBtn = (Button) findViewById(R.id.direct_register);

        directBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (agreeCkb.isChecked()) {
                    attemptLogin();
                } else {
                    Toast.makeText(PhoneLoginActivity.this, "请同意用户协议", Toast.LENGTH_LONG).show();
                }
            }
        });

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE ) == PackageManager.PERMISSION_GRANTED) {
            TelephonyManager mTelephonyManager = (TelephonyManager) this.getSystemService(this.TELEPHONY_SERVICE);

            // 获取手机号码
            mobile = mTelephonyManager.getLine1Number();
            mobileTxt.setText("本机号码：" + mobile);
            if ( mobile.equals("") ){
                finish();
                Intent intent = new Intent();
                intent.setClass(PhoneLoginActivity.this,RegisterActivity.class);
                startActivity(intent);

            }
//            mobileTxt.setText( "本机号码：" + mobile.substring(0,4) + "***" + mobile.substring(7,mobile.length()));
        }else {
            ActivityCompat.requestPermissions(PhoneLoginActivity.this,  new String[]{  Manifest.permission.READ_PHONE_STATE}, PERMISSION_REQUEST_PHONE);
        }

    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }


    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {

            case PERMISSION_REQUEST_PHONE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED ) {
                    try{
                        TelephonyManager mTelephonyManager = (TelephonyManager) this.getSystemService(this.TELEPHONY_SERVICE);
                        mobile = mTelephonyManager.getLine1Number();
                        mobileTxt.setText( "本机号码：" + mobile);
//                        mobileTxt.setText( "本机号码：" + mobile.substring(0,4) + "***" + mobile.substring(7,mobile.length()));
                        if ( mobile.equals("") ){
                            finish();
                            Intent intent = new Intent();
                            intent.setClass(PhoneLoginActivity.this,RegisterActivity.class);
                            startActivity(intent);
                        }
                    }catch (SecurityException e) {
                        Common.alert(PhoneLoginActivity.this,"没有成功访问本机号码");
                        intent.setClass(PhoneLoginActivity.this, RegisterActivity.class);
                        startActivity(intent);
                    }
                } else {
                    intent.setClass(PhoneLoginActivity.this, RegisterActivity.class);
                    startActivity(intent);
                }

                finish();
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {

        AsyncTask<Void,Void, LoginResponse> loadTask =
                new AsyncTask<Void, Void, LoginResponse>() {
                    @Override
                    protected LoginResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<LoginResponse> responseCall = svc.login(mobile,"*");
                        try {
                            LoginResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                    @Override
                    protected void onPostExecute(final LoginResponse response) {

                        if(response != null && !response.isSuccess() ){
                            Map<String,String > content = response.getContent();
                            setLogin(getApplication(), Integer.parseInt(response.getUserid())  );

                            finish();

                            Intent intent = new Intent();
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            intent.setClass(PhoneLoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        }else{
                            Common.alert(PhoneLoginActivity.this,response.getMessage());
                        }

                    }
                };
        loadTask.execute((Void)null);
    }


    public static void setLogin(Application application, Integer userId) {
        SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);
        SharedPreferences.Editor editor = shared.edit();
        editor.putString("snailview", "");
        editor.putString("location", "");
        editor.putString("title", "");
        editor.putInt("message_num", 0);

        editor.putBoolean("logged", true);
        editor.putInt("userId", userId);
        WoyaoooApplication.userId = userId;
        editor.commit();
    }
}

